import Vue from 'vue'
import store from '../store'
import { getSchoolInfo } from 'services/school/auth'
import { getCompanyInfo } from 'services/company/auth'
import { getStudentInfo } from 'services/student/auth'
import { EVENT_USER_INFO } from 'constants/'
// import { getTreeNodeById } from 'utils'

const whiteList = [
  '/login',
  '/401',
  '/404',
  '/test',
  '/register-school',
  '/register-company',
  '/register-student',
  '/find-pass'
]

export default async function auth({ path }, next) {
  try {
    if (whiteList.indexOf(path) !== -1) {
      next()
      return
    }
    const clientType = store.state.clientType
    // if (!getTreeNodeById(store.state.menus, path, 'path')) {
    //   next('/401')
    //   return
    // }
    if (whiteList.indexOf(path) === -1 && !store.state.userInfo) {
      let service
      if (clientType === 'school') {
        service = getSchoolInfo
      } else if (clientType === 'company') {
        service = getCompanyInfo
      } else {
        service = getStudentInfo
      }
      const { data } = await service()
      Vue.prototype.$bus.$emit(EVENT_USER_INFO, data)
      const { needFillup } = data
      if (needFillup) {
        if (clientType === 'school') {
          next('/fillup-school')
        } else if (clientType === 'company') {
          next('/fillup-company')
        } else {
          next('/fillup-student')
        }
        return
      }
    }
    next()
  } catch (err) {
    Vue.prototype.$bus.$emit(EVENT_USER_INFO, null)
    next('/login')
  }
}
